<template>
  <el-dialog class='subject-status-add-record' title="复制eCRFs" width="800px" :show-close='true'
             :visible.sync="copyVisible" :close-on-click-modal="false" :before-close="handleClose">
    <div>
      <el-form :rules="rules" ref="formRef" size="mini" :model="formData" label-width="140px">
        <el-form-item label="选择项目：" prop="originalProjectId">
          <el-select v-model="formData.originalProjectId" placeholder="请选择" style="width: 80%" @change="handleSelectProjectChange">
            <el-option v-for="item in sourceProjectList" :key="item.id" :label="item.projectCode + item.projectName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择版本：" prop="originalDatabaseId">
          <el-radio-group v-model="formData.originalDatabaseId" @change="handleRadioChange">
            <el-radio v-for="item in databaseVersionList" :key="item.id" :label="item.id">{{ item.databaseVersion }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择表单：">
          <el-table 
            :data="eCRFDesignList" 
            ref="multipleTable"
            stripe 
            style="width: 100%" 
            size="mini" 
            row-key="id"
            @selection-change="handleSelectionChange"
            :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
            :tree-props="{ children: 'children' }">
            <el-table-column
              type="selection"
              width="50">
            </el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="50">
            </el-table-column>
            <el-table-column
              label="表名"
              align="center"
              prop="surfaceName"
              width="200">
            </el-table-column>
            <el-table-column
              align="center"
              label="表"
              prop="surface"
              width="200">
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button :loading='loading' size="small" type="primary" @click="handleSave">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { mapActions } from 'vuex'

export default {
  props: {
    sortData: Object,
    copyVisible: Boolean,
    sourceProjectList: Array,
    currentECRFList: Array,
  },
  data() {
    return {
      rules: {
        originalProjectId: [{ required: true, message: '请选择', trigger: 'blur' }],
        originalDatabaseId: [{ required: true, message: '请选择', trigger: 'blur' }]
      },
      loading: false,
      databaseVersionList: [],
      formData: {},
      eCRFDesignList: [],
      selectedRows: [],
      originalCrfnameList: []
    }
  },

  methods: {
    ...mapActions('eCRFDesign', ['sortCrfDesignList', 'qryProjectDatabaseVersionNpLoading', 'qryDesignListNoLoading', 'copyECRFsAPI']),
    ...mapActions('solutionVersion', ['qryProjectDatabaseVersionNpLoading']),

    // 关闭取消
    handleClose() {
      this.formData = {}
      this.eCRFDesignList = []
      this.databaseVersionList = []
      this.$refs.multipleTable.clearSelection()
      this.$emit('handleCopyCancel')
    },

    // 源项目change事件
    handleSelectProjectChange(value) {
      if (value) {
        this.eCRFDesignList = []
        const params = {
          projectId: value
        }
        this.qryProjectDatabaseVersionNpLoading({ params }).then((res) => {
          const { data, code } = res
          if (code === 200) {
            this.databaseVersionList = data || []
            // this.formData.originalDatabaseId = data[0].id
            this.$set(this.formData, 'originalDatabaseId', data[0].id)
            this.handleRadioChange(data[0].id)
          }
        })
      }
    },

    handleRadioChange(value) {
      console.log('value', value)
      const params = {
        projectId: this.formData.originalProjectId,
        databaseId: value,
        databaseVersion: '0'
      }
      this.qryDesignListNoLoading({ params }).then((res) => {
        const { data, code } = res
        if (code === 200) {
          this.eCRFDesignList = data
        }
      })
    },

    // 选择数据
    handleSelectionChange(val) {
      this.selectedRows = val
      const list = []
      this.selectedRows.map((sItem, sIndex) => {
        list.push(sItem.surface)
      })
      this.originalCrfnameList = list
    },

    // 保存提交
    handleSave() {
      this.loading = true
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}
          const data = {
            newProjectId: localStorage.getItem('sys-project-id') || '',
            newDatabaseId: databaseInfo.databaseId,
            newDatabaseVersion: databaseInfo.databaseVersion,
            newEnvironment: 0,
            
            originalEnvironment: 0,
            originalCrfnameList: this.originalCrfnameList,
            originalDatabaseId: this.formData.originalDatabaseId,
            originalDatabaseVersion: 0,
            originalProjectId: this.formData.originalProjectId,
            sortNum: this.currentECRFList[this.currentECRFList.length - 1].sort
          }
          console.log(8888888, this.originalCrfnameList, this.currentECRFList)
          let flag = true
          this.originalCrfnameList.map((oItem, oIndex) => {
            this.currentECRFList.map((cItem, cIndex) => {
              if (cItem.surface === oItem) {
                flag = false
                this.$message.warning(`${cItem.surfaceName}在当前数据库中已存在，无法复制!`)
                return ''
              }
            })
          })
          if (flag) {
            this.copyECRFsAPI({ data }).then(res => {
              const { code } = res
              if (code === 200) {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.$refs.formRef.resetFields()
                this.$emit('handleCopyCancel', 'refresh')
              }
              this.loading = false
            })
          } else {
            this.loading = false
          }
          
        } else {
          this.loading = false
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import './add-design.scss';
</style>
